/**
 * 
 */
package org.xlab.baseframework.test.platform.job;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.xlab.baseframework.exception.ObjectNotFoundException;
import org.xlab.baseframework.test.platform.common.comparator.BizTransactionLogComparator;
import org.xlab.baseframework.test.platform.domain.BizTransactionLog;
import org.xlab.baseframework.test.platform.domain.EpcCache;
import org.xlab.baseframework.test.platform.domain.enumerate.SynchronizedInditify;
import org.xlab.baseframework.test.platform.service.api.IBizTransactionLogService;

/**
 * @author makubex
 * 
 */
public class TransactionDataProcessor {
	private static final Logger log = Logger
			.getLogger(TransactionDataProcessor.class);

	private IBizTransactionLogService bizTransactionLogService;

	/**
	 * @return the bizTransactionLogService
	 */
	public IBizTransactionLogService getBizTransactionLogService() {
		return bizTransactionLogService;
	}

	public void process() {
		log.debug("Data processing...");
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MINUTE, -15);
		try {
			List<BizTransactionLog> allTransaction = bizTransactionLogService
					.findAllByMaxCreatedTime(c.getTime());
			log.debug("Sorting..");
			Collections.sort(allTransaction, new BizTransactionLogComparator());
			log.debug(allTransaction.size()
					+ " transactions will be synchronized! See the details below:");
			for (BizTransactionLog trans : allTransaction) {
				if (bizTransactionLogService.checkLogic(trans, EpcCache.getInstance().getInventory())) {
					trans.setSynchronizedInd(SynchronizedInditify.Y);
					trans.setLastUpdatedTime(new Date());
					bizTransactionLogService.update(trans);
					if (trans.getCommandId().equalsIgnoreCase("GI"))
						EpcCache.getInstance().deleteEpcInfo(trans.getEpcNo(),
								trans.getCreatedBy(), trans.getCreatedTime());
					else
						EpcCache.getInstance().saveOrUpdateEpcInfo(
								trans.getEpcNo(), trans.getLocation(),
								trans.getCommandId(), trans.getCreatedBy(),
								trans.getCreatedTime());
					log.debug("Done!");
				} else {
					log.error("Error Occurred!!");
					break;
				}
			}
			log.debug("Synchronizing acomplished!");
		} catch (ObjectNotFoundException e) {
			log.debug("Nothing will be synchronized!");
		}
	}

	/**
	 * @param bizTransactionLogService
	 *            the bizTransactionLogService to set
	 */
	public void setBizTransactionLogService(
			IBizTransactionLogService bizTransactionLogService) {
		this.bizTransactionLogService = bizTransactionLogService;
	}
}
